package com.demo.service;

import com.demo.model.common.Pagination;
import com.demo.model.common.PaginationDTO;
import com.demo.model.domain.ProductInfoMoreDO;
import com.demo.model.domain.SpringbootDemoMoreDO;
import com.demo.model.dto.*;
import com.demo.model.entity.baoxian.InsurancePolicyOrderMainEntity;
import com.demo.model.entity.baoxian.InsurancePolicyPaymentEntity;
import com.demo.model.entity.baoxian.PlanbookInsuranceCompanyEntity;
import com.demo.model.entity.baoxian.SpringbootDemoEntity;
import com.demo.model.enums.BusinessErrorEnum;
import com.demo.model.exceptions.BusinessException;
import com.demo.repository.baoxian.PlanbookInsuranceCompanyRepository;
import com.demo.repository.baoxian.SalesInsureProductRepository;
import com.demo.repository.baoxian.SpringbootDemoRepository;
import com.demo.repository.sharding.InsurancePolicyOrderMainRepository;
import com.demo.repository.sharding.InsurancePolicyPaymentRepository;
import com.demo.repository.sharding.SpringbootDemoShardingRepository;
import com.demo.repository.tob.SpringbootDemoTobRepository;
import com.demo.service.convert.mapper.InsurancePolicyOrderMainMapper;
import com.demo.service.convert.mapper.PlanbookInsuranceCompanyMapper;
import com.demo.service.convert.mapper.ProductInfoMapper;
import com.demo.service.convert.mapper.SpringbootDemoMapper;
import com.demo.uitls.SnowflakeUtil;
import com.demo.uitls.TransformerUtils;
import com.demo.uitls.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author DongXL
 * @Create 2017-12-22 14:06
 */

@Service
@Slf4j
public class DemoService {

    @Resource
    private PlanbookInsuranceCompanyRepository planbookInsuranceCompanyRepository;
    @Resource
    private SalesInsureProductRepository salesInsureProductRepository;
    @Resource
    private SpringbootDemoRepository springbootDemoRepository;
    @Resource
    private SpringbootDemoShardingRepository springbootDemoShardingRepository;
    @Resource
    private SpringbootDemoTobRepository springbootDemoTobRepository;
    @Resource
    private InsurancePolicyOrderMainRepository insurancePolicyOrderMainRepository;
    @Resource
    private InsurancePolicyPaymentRepository insurancePolicyPaymentRepository;

    @Value("${mine.configuration.value}")
    private String mineValue;


    public SpringbootDemoDTO addSpringbootDemo(SpringbootDemoDTO dto) {
        if (dto.getId() != null) {
            throw new BusinessException(BusinessErrorEnum.COMMON_DATA_EXISTS);
        }
        SpringbootDemoEntity demoEntity = SpringbootDemoMapper.INSTANCE.toEntity(dto);
        demoEntity.setId(SnowflakeUtil.INSTANCE.nextId());
        springbootDemoRepository.save(demoEntity);
        return SpringbootDemoMapper.INSTANCE.toDTO(demoEntity);
    }

    public void deleteSpringbootDemo(Long demoId) {
        SpringbootDemoEntity persistent = springbootDemoRepository.findOne(demoId);
        persistent.setDeleted(Boolean.TRUE);
        springbootDemoRepository.save(persistent);
    }

    /**
     * CachePut可以使用 #result
     *
     * @param demoId
     * @param dto
     * @return
     */
    public SpringbootDemoDTO updateSpringbootDemo(Long demoId, SpringbootDemoDTO dto) {
        SpringbootDemoEntity persistent = springbootDemoRepository.findOne(demoId);
        persistent.setCname(dto.getCname());
        springbootDemoRepository.save(persistent);
        return SpringbootDemoMapper.INSTANCE.toDTO(persistent);
    }

    @Cacheable(cacheNames = "demo", key = "#demoId+''")
    public SpringbootDemoDTO getSpringbootDemo(Long demoId) {
        SpringbootDemoEntity demoEntity = springbootDemoRepository.findOne(demoId);
        return SpringbootDemoMapper.INSTANCE.toDTO(demoEntity);
    }

    public List<SpringbootDemoDTO> getSpringbootDemoList() {
        List<SpringbootDemoEntity> demoEntityList = springbootDemoRepository.getAllByDeletedFalse();
        return SpringbootDemoMapper.INSTANCE.toDTO(demoEntityList);
    }

    /**
     * 熔断 当执行时间超过5s则进入失败处理方法 {@link DemoService#helloFallbackMethod}
     *
     * @param id
     * @return
     */
    public PlanbookInsuranceCompanyDTO getPlanbookInsuranceCompany(Long id) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("InterruptedException", e);
            Thread.currentThread().interrupt();
        }
        PlanbookInsuranceCompanyEntity entity = planbookInsuranceCompanyRepository.findOne(id);
        return PlanbookInsuranceCompanyMapper.INSTANCE.toDTO(entity);
    }

    public PlanbookInsuranceCompanyDTO helloFallbackMethod(Long id) {
        System.out.println("fallback 参数值为:" + id);
        PlanbookInsuranceCompanyDTO dto = new PlanbookInsuranceCompanyDTO();
        dto.setId(1L);
        return dto;
    }

    public List<ProductInfoMoreDTO> multiSearch1(Integer type) {
        List<ProductInfoMoreDO> doList = salesInsureProductRepository.getProductInfoMoreList(type);
        return ProductInfoMapper.INSTANCE.toDTO(doList);
    }

    public List<ProductInfoMoreDTO> multiSearch2(Integer type) {
        List<Map<String, Object>> mapList = salesInsureProductRepository.getProductInfoMoreListWithMap(type);
        List<ProductInfoMoreDO> doList = TransformerUtils.INSTANCE.transformMapList2ObjectList(mapList, ProductInfoMoreDO.class);
        return ProductInfoMapper.INSTANCE.toDTO(doList);
    }

    public List<ProductInfoMoreDTO> multiSearchWithDynamicParams(Integer type) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        List<ProductInfoMoreDO> doList = salesInsureProductRepository.getProductInfoMoreListWithDynamicParams(type, sort);
        return ProductInfoMapper.INSTANCE.toDTO(doList);
    }

    public PaginationDTO multiSearchWithDynamicParamsByPagination1(Pagination pagination, Integer type) {
        Integer totalCount = salesInsureProductRepository.countProductInfoMoreListWithDynamicParams(type);
        List<ProductInfoMoreDTO> list = null;
        if (totalCount > 0) {
            Pageable pageable = Pagination.createPageable(pagination, "id", Sort.Direction.DESC.name());
            List<ProductInfoMoreDO> doList = salesInsureProductRepository.getProductInfoMoreListWithDynamicParams(type, pageable);
            list = ProductInfoMapper.INSTANCE.toDTO(doList);
        }
        return PaginationDTO.createNewInstance(pagination, totalCount, list);
    }

    /**
     * @serviceversion 1.0.0
     * @serviceauthor 脏老师
     * @servicegroup 用户模块
     * @servicename 查询用户
     * @service List<User> getUserList(Pagination pagination, Integer type))
     * @servicedescription test 接口描述
     * @serviceparam (pagination) {Number} start description
     * @serviceparam (pagination) {Number} end description
     * @serviceparam (pagination) {String} name description
     * @serviceparamexample pagination
     * {"start":1,"end":2,"name":"23213"}
     * @serviceparam (type) {String} type description
     * @serviceparamexample type
     * 1
     * @serviceparam (m) {String} m description
     * @serviceparamexample m
     * test
     * @serviceresult (结果) {Number} start description
     * @serviceresult (结果) {Number} end description
     * @serviceresult (结果) {String} name description
     * @serviceresultexample 结果示例
     * {"start":1,"end":2,"name":"23213"}
     */
    public List<SpringbootDemoMoreDTO> multiDataSourceSearch() {
        List<SpringbootDemoMoreDO> doList = springbootDemoRepository.multiDataSourceSearch();
        return SpringbootDemoMapper.INSTANCE.toMoreDTO(doList);
    }

    /**
     * @serviceVersion 2.0.0
     * @serviceAuthor dongxl
     * @serviceGroup 案例
     * @serviceName 分页查询
     * @service PaginationDTO<ProductInfoMoreDTO> multiSearchWithDynamicParamsByPagination2(Pagination pagination, Integer type)
     * @serviceDescription service层doc测试
     * @serviceParam (pagination) {Number} pageNum  第几页
     * @serviceParam (pagination) {Number} pageSize 每页数量
     * @serviceParam (pagination) {Number} totalRow 总数
     * @serviceParam (pagination) {Number} totalPage 总页数
     * @serviceParam (pagination) {Number} startRow 开始位置
     * @serviceParam (type) {Number} type 类型
     * @serviceParamExample pagination
     * {"pageNum":1,"pageSize":50,"totalRow":2,"totalPage":1,"startRow":0,"type":1}
     * @serviceParamExample type
     * type = 1
     * @serviceResult (结果) {Number} pageNum 第几页
     * @serviceResult (结果) {Number} pageSize 每页数量
     * @serviceResult (结果) {Number} startRow 开始位置
     * @serviceResult (结果) {Number} totalRow 总数
     * @serviceResult (结果) {Number} totalPage 总页数
     * @serviceResult (结果) {String} orderProperty 排序字段
     * @serviceResult (结果) {String} orderDirection 升降序
     * @serviceResult (结果) {Array} list 列表
     * @serviceResult (结果) {Number} list.companyId 公司ID
     * @serviceResult (结果) {String} list.companyName 公司名字
     * @serviceResult (结果) {String} list.companyLogoUrl 公司logo
     * @serviceResult (结果) {Number} list.productId 产品ID
     * @serviceResult (结果) {String} list.productName 产品名称
     * @serviceResult (结果) {Number} list.productType 产品类型
     * @serviceResultExample 结果示例
     * {"pageNum":1,"pageSize":50,"totalRow":639,"totalPage":13,"orderProperty":"companyId","orderDirection":"DESC","list":[{"companyId":10091,"companyName":"华海保险","companyLogoUrl":"http://img.winbaoxian.com/autoUpload/insurance/huahai.jpg","productId":100842,"productName":"e生无忧百万医疗2018","productType":2}],"startRow":0}
     */
    public PaginationDTO<ProductInfoMoreDTO> multiSearchWithDynamicParamsByPagination2(Pagination pagination, Integer type) {
        Pageable pageable = Pagination.createPageable(pagination, "companyId", Sort.Direction.DESC.name());
        Page<ProductInfoMoreDO> page = salesInsureProductRepository.getProductInfoMoreListWithDynamicParams2(type, pageable);
        return PaginationDTO.createNewInstance(page, ProductInfoMoreDTO.class);
    }

    public InsurancePolicyOrderMainDTO getInsurancePolicyOrderMainList(String orderNo) {
        InsurancePolicyOrderMainEntity entity = insurancePolicyOrderMainRepository.findByOrderNo(orderNo);
        return InsurancePolicyOrderMainMapper.INSTANCE.toDTO(entity);
    }

    public List<SpringbootDemoDTO> getDemoByOrderNo(String orderNo) {
        List<SpringbootDemoEntity> entityList = springbootDemoRepository.findAllByOrderNo(orderNo);
        return SpringbootDemoMapper.INSTANCE.toDTO(entityList);
    }

    public void saveMainOrder(String orderNo) {
        InsurancePolicyOrderMainEntity orderMainEntity = new InsurancePolicyOrderMainEntity();
        orderMainEntity.setOrderNo(orderNo);
        orderMainEntity.setStatus(50);
        insurancePolicyOrderMainRepository.save(orderMainEntity);
        System.out.println(orderMainEntity.getOrderNo());
        InsurancePolicyPaymentEntity policyPaymentEntity = new InsurancePolicyPaymentEntity();
        policyPaymentEntity.setPayType(1);
        policyPaymentEntity.setOrderNo(orderNo);
        policyPaymentEntity.setUuid(UUIDUtil.INSTANCE.randomUUID());
        insurancePolicyPaymentRepository.save(policyPaymentEntity);
        SpringbootDemoEntity demo = new SpringbootDemoEntity();
        demo.setOrderNo(orderNo);
        springbootDemoShardingRepository.save(demo);
        System.out.println("ssss");
    }

}
